package com.iflytek.springboot_medicine.service.impl;

import com.iflytek.springboot_medicine.common.Page;
import com.iflytek.springboot_medicine.entity.Apply;
import com.iflytek.springboot_medicine.entity.User;
import com.iflytek.springboot_medicine.mapper.AppMapper;
import com.iflytek.springboot_medicine.service.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class AppService {
    @Autowired
    private AppMapper appMapper;

    @Autowired
    private UserServiceImpl userServiceImpl;

    @Autowired
    private UserRepository  userRepository;


    public Apply selectUserByid(Integer id) {
        return appMapper.selectById(id);
    }

    public void insertUser(Apply user) {
//        Date d1= new Date();
//        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        Date date = sdf1.format(d1);
        user.setApplyDate(user.getApplyDate());
        appMapper.insertuser(user);
    }

    public void delectUser(Integer id) {
        appMapper.delectuser(id);
    }

    public void delectBatch(List<Integer> ids) {
        for (Integer id : ids) {
            appMapper.delectuser(id);
        }
    }

    public void updateUser(Apply user) {
//        // 更新申请状态
//        appMapper.updateuser(user);

        // 根据申请状态更新用户角色
        Optional<User> dbUser = userRepository.findById(user.getUserId());
        if (dbUser.isPresent()) {
            User userToUpdate = dbUser.get();
            if ("通过".equals(user.getStatus())) {
                userToUpdate.setRole("merchant"); // 通过申请，设置为管理员角色
                user.setStatus(user.getStatus());

            } else {
                userToUpdate.setRole("customer"); // 不通过申请，设置为普通用户角色
                user.setStatus(user.getStatus());
            }
            userRepository.save(userToUpdate);
        }

        // 如果申请通过，则删除申请记录
        if ("通过".equals(user.getStatus())) {
            appMapper.delectuser(user.getId());
        }
    }

    public Page<Apply> selectByPage(Integer pageNum, Integer pageSize) {
        Integer skipNum = (pageNum - 1) * pageSize; //计算出来

        Page<Apply> page = new Page<>();
        List<Apply> userList = appMapper.selectBypage(skipNum,pageSize);
        Integer total =  appMapper.selectCountByPage();
        page.setTotal(Long.valueOf(total));
        page.setList(userList);

        return  page;

    }

//    public void updateStatus(Apply user) {
//        if (user.getStatus().equals("") || user.getStatus() == null) {
//            user.setStatus(0);
//        }
//        appMapper.updatestatus(user);
//    }

}
